/*************************************************************************
> File Name: stack.c
> Author: icebear
> Mail: 3322366195@qq.com
> Created Time: 2023-07-24 20:07:32
> Description: 基于链表的栈
************************************************************************/
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
    printf("create: \n");
    Stack *stack = create();
    printf("push: 1-9\n");
    for (int i = 0; i < 10; i++)
    {
        push(stack, i);
    }
    printf("size: %d\n", size(stack));
    printf("isEmpty: %d\n", isEmpty(stack));
    printf("peek: %d\n", peek(stack));
    printf("pop:10 item \n");
    for (int i = 0; i < 10; i++)
    {
        printf("%3d", pop(stack));
    }
    printf("\n");
    printf("isEmpty: %d\n", isEmpty(stack));
    printf("size: %d\n", size(stack));
    printf("\n");
    return 0;
}

Stack *create()
{
    Stack *stack = malloc(sizeof(Stack));
    // stack->head = malloc(sizeof(Node));
    stack->size = 0;
}
int destory(Stack *stack)
{
    Node *temp;
    while (stack->head != NULL)
    {
        temp = stack->head;
        stack->head = stack->head->next;
        free(temp->data); // 逐级释放
        free(temp);
    }
    free(stack);
}
void push(Stack *stack, int item)
{
    if (stack->size == 0) // 头结点
    {
        stack->head = malloc(sizeof(Node));
        stack->head->data = malloc(sizeof(Data));
        stack->head->next = NULL;
        stack->head->data->value = item;
        stack->size++;
    }
    else
    {
        // 非头结点————————头插法
        Node *temp = stack->head;
        stack->head = malloc(sizeof(Node));
        stack->head->data = malloc(sizeof(Data));
        stack->head->next = temp;
        stack->head->data->value = item;
        stack->size++;
    }
}
int pop(Stack *stack)
{
    if (stack->size == 0)
    {
        return -1;
    }
    int item = stack->head->data->value;
    Node *temp = stack->head;
    stack->head = stack->head->next;
    free(temp->data);
    free(temp);
    stack->size--;
    return item;
}
int peek(Stack *stack)
{
    int item = stack->head->data->value;
    return item;
}
int isEmpty(Stack *stack)
{
    if (stack->size == 0)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
int size(Stack *stack)
{
    return stack->size;
}